import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'
import { Observable } from 'rxjs'
import { tap } from 'rxjs/operators'
import { Request } from 'express'

/**
 * 日志拦截器
 * 记录请求和响应信息
 */
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>()
    const { method, url } = request
    const now = Date.now()

    console.log(`[${new Date().toISOString()}] ${method} ${url} - 开始处理`)

    return next.handle().pipe(
      tap(() => {
        const duration = Date.now() - now
        console.log(`[${new Date().toISOString()}] ${method} ${url} - 处理完成 (+${duration}ms)`)
      })
    )
  }
}
